<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use addons\yunfood\library\Super;
use think\Model;
use traits\model\SoftDelete;

/**
 * 购物车模型
 */
class Cart extends Model
{
    use ModelTrait;

    // 表名,不含前缀
    protected $name = 'yunfood_cart';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    protected $resultSetType = 'collection';

    // 商品名称s
    public function getGoodsNamesAttr($value, $data)
    {
        $goodsData = $data['goods_data'] ? json_decode($data['goods_data'], true) : [];

        return Logic::getGoodsNames($goodsData);
    }

    public static function getGoodsAlias($goodsId, $goodsData)
    {
        $goodsAttrs = [$goodsId];
        if ($goodsData) {
            if ($specData = $goodsData['spec_data'] ?? null) {
                $goodsAttrs[] = 'sku';
                $goodsAttrs[] = $specData['id'];
            }
            if ($attrList = $goodsData['attr_list'] ?? []) {
                $attrIds = [];
                foreach ($attrList as $item) {
                    $attrIds[] = $item['id'] . '_' . $item['item'];
                }
                natsort($attrIds);
                $goodsAttrs[] = 'attrs';
                $goodsAttrs = array_merge($goodsAttrs, $attrIds);
            }
            if ($noteList = $goodsData['note_list'] ?? []) {
                natsort($noteList);
                $goodsAttrs[] = 'notes';
                $goodsAttrs = array_merge($goodsAttrs, $noteList);
            }
            if ($addonList = $goodsData['addon_list'] ?? []) {
                $addonMap = array_column($addonList, null, 'id');
                $addonIds = array_keys($addonMap);
                natsort($addonIds);
                $goodsAttrs[] = 'addons';
                $goodsAttrs = array_merge($goodsAttrs, $addonIds);
            }
        }

        return implode(':', $goodsAttrs);
    }

    public static function getCartList($userId, $shopId = 0)
    {
        $result = [];

        // 数据列表
        $goodsList = Cart::where(['shop_id' => $shopId, 'user_id' => $userId])
            ->order(['id' => 'DESC'])->select();
        if (count($goodsList) > 0) {
            // 菜品相关数据
            $foodMap = $foodSkuMap = [];
            $foodIds = array_column($goodsList->toArray(), 'goods_id');
            $foodList = Food::where('id', 'in', $foodIds)->show()->select();
            if (count($foodList)) {
                $foodMap = Super::arrayIndex($foodList, 'id');
            }
            $foodSkuIds = array_column($goodsList->toArray(), 'goods_sku_id');
            if ($foodSkuIds = array_filter($foodSkuIds)) {
                $foodSkuList = FoodSku::where('id', 'in', $foodSkuIds)->show()->select();
                if (count($foodSkuList)) {
                    $foodSkuMap = Super::arrayIndex($foodSkuList, 'id');
                }
            }

            // 处理价格
            $invalidIds = [];
            foreach ($goodsList as $item) {
                if (! $food = $foodMap[$item['goods_id']] ?? null) {
                    $invalidIds[] = $item['id'];
                    continue;
                }
                $goodsPrice = $food->price;
                if ($item['goods_sku_id']) {
                    if (! $foodSku = $foodSkuMap[$item['goods_sku_id']] ?? null) {
                        $invalidIds[] = $item['id'];
                        continue;
                    }
                    $goodsPrice = $foodSku->price;
                }
                $goodsData = $item['goods_data'] ? json_decode($item['goods_data'], true) : [];

                // 加菜数据
                if ($addonList = $goodsData['addon_list'] ?? []) {
                    $addonMap = array_column($addonList, null, 'id');
                    $addonIds = array_keys($addonMap);
                    $foodList = Food::where('id', 'in', $addonIds)->where('multi_spec', 0)->show()->select();
                    if (count($foodList) != count($addonList)) {
                        $invalidIds[] = $item['id'];
                        continue;
                    }
                    foreach ($foodList as $tItem) {
                        $addonInfo = $addonMap[$tItem->id];
                        if ($tItem->count_left < ($addonInfo['count'] ?? 0)) {
                            $invalidIds[] = $tItem['id'];
                            break;
                        }
                        $goodsPrice += $tItem->price;
                    }
                }
                $result[] = Super::arrayGetSet($item, [
                    'id',
                    'goods_alias',
                    'goods_id',
                    'goods_name',
                    'goods_names',
                    'goods_cover',
                    'goods_price' => function ($tItem) use ($goodsPrice) {
                        return $goodsPrice;
                    },
                    'goods_data'  => function ($item) {
                        return json_decode($item->goods_data, true);
                    },
                    'goods_count'
                ]);
            }
            if ($invalidIds) {
                Cart::destroy($invalidIds);
            }
        }

        return $result;
    }
}
